package ch.bfh.fbi.mobiComp2013.sensornet.implementation;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import ch.bfh.fbi.mobiComp2013.sensornet.definition.SensorCommunication;
import ch.bfh.fbi.mobiComp2013.sensornet.definition.SensorCommunicationManager;
import ch.bfh.fbi.mobiComp2013.sensornet.definition.SensorMessage;
import ch.quantasy.communication.channel.definition.ChannelManager;
import ch.quantasy.communication.channel.definition.MessageReceiver;
import ch.quantasy.communication.channel.definition.MessageSender;
import ch.quantasy.communication.channel.implementation.DefaultChannelManager;
import ch.quantasy.communication.channel.implementation.udp.UDPBroadcastChannel;
import ch.quantasy.communication.chat.definition.ChatMessage;

public class MySensorManager implements SensorCommunicationManager {
	private final SensorCommunication sensorCommunication;
	private ChannelManager<SensorMessage> channelManager;
	
	public MySensorManager(final SensorCommunication sensorCommunication) {
		initNetworkElements();
		channelManager.getMessageReceiver().addMessageReceiverListener(this);
		this.sender = channelManager.getMessageSender();
		this.sensorCommunication = sensorCommunication;
	}
	
	private void initNetworkElements() {
		try {
			// http://en.wikipedia.org/wiki/Multicast_address
			// http://code.google.com/p/boxeeremote/wiki/AndroidUDP
			this.channelManager = new DefaultChannelManager<SensorMessage>(
					new UDPBroadcastChannel<SensorMessage>(
							InetAddress.getByName("224.0.2.4"), 4444, 2));
		} catch (final UnknownHostException e) {
			e.printStackTrace();
			// Exception-handling
		} catch (final IOException e) {
			e.printStackTrace();
			// Exception-handling
		}
	}
	

	@Override
	public SensorCommunication getSensorCommunication() {
		return this.sensorCommunication;
	}

	// Things required by SensorMessageReceiver
	@Override
	public void messageReceived(final MessageReceiver<SensorMessage> receiver,
			final SensorMessage sensorMessage) {
		this.sensorCommunication.onMessageReceived(sensorMessage);
	}	

	// Things required by SensorMessageSender
	private SensorMessage latestMessage;
	private final MessageSender<SensorMessage> sender;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * ch.quantasy.communication.chat.implementation.ChatMessageSender
	 * #send(ch.quantasy.communication.chat.definition.ChatMessage)
	 */
	@Override
	public void send(final SensorMessage message) {
		this.latestMessage = message;
		this.sender.sendRequest(this);
	}

	@Override
	public SensorMessage getLatestMessage() {
		return this.latestMessage;
	}

	@Override
	public void messageDelivered(final SensorMessage channelMessage) {
		this.sensorCommunication.onMessageDelivered();
	}
}
